#include "work.h"
#include "declares.h"
#include <stdlib.h>
#include <unistd.h>
#include "led.h"
#include <pthread.h>
#include <signal.h>

int task_cancel_req = 0;
int is_running = 0;
static pthread_t th;
static pid_t pid;
static int count = 1;

void run()
{
    DEBUG("%s pgid %d", __FILE__, getpgid(0));
    pid = start_work();
    
    if (pid == -1)
    {
        DEBUG("pid: -1");
        exit(EXIT_FAILURE);
    }
    is_running = 1;
    pthread_kill(led_th, SIGUSR1);
    while (1)
    {
        if (task_cancel_req)
        {
            DEBUG("got task_cancel_req");
            clean();
            is_running = 0;
            return;
        }
        int wstatus;
        if (waitpid(pid, &wstatus, WNOHANG) == pid)
        {
            DEBUG("task exited");
            if (count++ == 2)
            {
                count = 1;
                is_running = 0;
                return;
            }
            pid = start_work();
        }
        sleep(1);
    }
}

void run_task()
{
    pthread_create(&th, NULL, run, NULL);
}

void task_join()
{
    pthread_join(th, NULL);
}